import { defineStore } from "pinia";

const useTodosStore = defineStore("todos", {
  // vue2的data
  state() {
    return {
      list: JSON.parse(localStorage.getItem("todos")) || [
        {
          id: 1,
          name: "吃饭",
          done: true,
        },
        {
          id: 2,
          name: "睡觉",
          done: true,
        },
        {
          id: 3,
          name: "敲代码",
          done: false,
        },
      ],
      filterArr: ["All", "Active", "Completed"],
      active: "All",
    };
  },
  getters: {
    isCheckAll() {
      // some 有一项符合条件就返回ture
      // every 每一项都符合才返回true,对于空数组，会返回true
      return this.list.length > 0 && this.list.every((v) => v.done);
    },
    // 统计未完成
    leftCount() {
      return this.list.filter((v) => !v.done).length;
    },
    // 过滤
    showList() {
      if (this.active === "All") {
        return this.list;
      } else if (this.active === "Active") {
        return this.list.filter((v) => !v.done);
      } else if (this.active === "Completed") {
        return this.list.filter((v) => v.done);
      }
    },
  },

  actions: {
    // 修改状态
    changeDone(id) {
      const obj = this.list.find((v) => v.id === id);
      obj.done = !obj.done;
    },
    // 删除数据
    del(id) {
      this.list = this.list.filter((v) => v.id !== id);
    },
    // 添加数据
    add(name) {
      this.list.unshift({
        id: +new Date(),
        name,
        done: false,
      });
    },
    // 全选/反选
    changeAll(bl) {
      this.list.forEach((item) => (item.done = bl));
    },
    // 清理已完成
    clearDone() {
      this.list = this.list.filter((v) => !v.done);
    },
    changeActive(active) {
      this.active = active;
    },
  },
});

// 1.必须掌握的写法
export default useTodosStore;
